
//  BHMyFansAndAttensionViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/22.
//  我的粉丝和我的关注（共用）

import UIKit

class BHCommonUserViewController: BHBaseViewController {

    // 0我的粉丝  1我的关注  2 趣玩的已报名用户列表 3赛事的已报名用户列表
    open var type: Int = 0
    var userId: String? // 不传查自己的
    var businessId: String?
    
    fileprivate var userArray: [BHUserListModel] = []
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        view.backgroundColor = .color_f8f8f8
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.regiseterNib(nibName: "BHMyAttensionUserCell")
        view.delegate = self
        view.dataSource = self
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.addSubview(self.tableView)
        if self.type == 0 {
            self.bh_navigationBar.title_label.text = "我的粉丝"
            self.loadFansService()
        }else if self.type == 1{
            self.bh_navigationBar.title_label.text = "我的关注"
            self.loadAttentionService()
        }else if self.type == 2{
            self.bh_navigationBar.title_label.text = "已报名用户"
            self.loadFunApplyUserService()
        }else if self.type == 3{
            self.bh_navigationBar.title_label.text = "已报名用户"
            self.loadGameApplyUserService()
        }
    
    }
    

   

}
extension BHCommonUserViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.userArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
}

extension BHCommonUserViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let back = UIView.init()
        back.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 10)
        back.backgroundColor = .color_f8f8f8
        return back
    }

    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BHMyAttensionUserCell", for: indexPath) as! BHMyAttensionUserCell
        let model = self.userArray[indexPath.section]
        cell.model = model
        cell.attentionBtn.addBtnAction(action: {[weak self] (_) in
            self?.attentionOrNotService(model: model)
        }, for: .touchUpInside)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.userArray[indexPath.section]
        BHRouter.shared.bh_goPersonalHome(userId: model.userId)
    }
}
 
// MARK: 处理数据
extension BHCommonUserViewController {
    func result(success: Bool,errorMsg: String,responseDic: [String:Any])  {
        SVProgressHUD.dismiss()
        if success == true {
            let result = BHJsonTool.decodeDicFromDic(dic: responseDic, key: "result")
            let total = BHJsonTool.decodeIntFromDic(dic: responseDic, key: "total")
            let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
            if self.page == 1 {
                self.tableView.endLoadWithNoMoreData(false)
                self.userArray.removeAll()
            }
            for item in record {
                let model = BHUserListModel.init()
                model.parseDic(item as! [String:Any])
                model.type = self.type
                self.userArray.append(model)
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
                
                if self.userArray.count >= total {
                    self.tableView.endLoadWithNoMoreData(true)
                }
            }
            
        }else {
            BHToast.toast(text: errorMsg)
            if self.page > 1 {
                self.page -= 1
            }
        }
    }
}

// 获取粉丝列表
extension BHCommonUserViewController {
    func loadFansService()  {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 20
        if self.userId != nil {
            dic["userId"] = self.userId!
        }
        
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.me_userInfo_fans_list_url, paramters: dic) { (success, errorMsg, responseDic) in
            self.result(success: success, errorMsg: errorMsg, responseDic: responseDic)
        }
    }
}

// 获取关注列表
extension BHCommonUserViewController {
    func loadAttentionService()  {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 20
        if self.userId != nil {
            dic["userId"] = self.userId!
        }
        
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.me_userInfo_attention_list_url, paramters: dic) { (success, errorMsg, responseDic) in
            self.result(success: success, errorMsg: errorMsg, responseDic: responseDic)
        }
    }
}

// 获取趣玩报名列表
extension BHCommonUserViewController {
    func loadFunApplyUserService()  {
        var dic: [String:Any] = [:]
        dic["pageNo"] = self.page
        dic["pageSize"] = 20
        dic["id"] = self.businessId!

        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.fun_detail_userApply_list_url, paramters: dic) { (success, errorMsg, responseDic) in
            self.result(success: success, errorMsg: errorMsg, responseDic: responseDic)
        }
    }
}

// 赛事详情的用户报名列表
extension BHCommonUserViewController {
    func loadGameApplyUserService()  {
        var dic: [String:Any] = [:]
        dic["eventId"] = self.businessId!

        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.get(url: String.game_detail_applyUserList_url, paramters: dic) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                let result = BHJsonTool.decodeArrayFromDic(dic: responseDic, key: "result")
                let total = BHJsonTool.decodeIntFromDic(dic: responseDic, key: "total")
                if self.page == 1 {
                    self.tableView.endLoadWithNoMoreData(false)
                    self.userArray.removeAll()
                }
                for item in result {
                    let model = BHUserListModel.init()
                    model.userName = BHJsonTool.decodeStringFromDic(dic: item as? [String:Any], key: "realname")
                    model.userAvatar = BHJsonTool.decodeStringFromDic(dic: item as? [String:Any], key: "avatar")
                    model.userId = BHJsonTool.decodeStringFromDic(dic: item as? [String:Any], key: "userId")
                    model.signName = BHJsonTool.decodeStringFromDic(dic: item as? [String:Any], key: "realname")
                    model.attentionFalg = BHJsonTool.decodeIntFromDic(dic: item as? [String:Any], key: "ifAttention")
                    
                    
                    model.type = self.type
                    self.userArray.append(model)
                }
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                    
                    if self.userArray.count >= total {
                        self.tableView.endLoadWithNoMoreData(true)
                    }
                }
                
            }else {
                BHToast.toast(text: errorMsg)
                if self.page > 1 {
                    self.page -= 1
                }
            }
        }
    }
}


extension BHCommonUserViewController {
    
    func attentionOrNotService(model: BHUserListModel) {
        SVProgressHUD.show()
        BHCommonService.attentionOrNotService(type: 5, businessId: model.userId) { (success, errorMsg) in
            SVProgressHUD.dismiss()
            if success == true {
                if model.attentionFalg == 1 {
                    model.attentionFalg = 0
                    BHToast.toast(text: "关注已取消")
                }else {
                    model.attentionFalg = 1
                    BHToast.toast(text: "已关注")
                }
                self.tableView.reloadData()
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
}
